package utils;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Created by sealer on 17/05/03.
 */
public class MailSender {
    private final transient Properties props = System.getProperties();
    private transient Session session;
    private String username;

    //手动输入smtpHost
    private MailSender(final String smtpHostName, final String username, final String password) {
        init(smtpHostName, username, password);
    }

    //自动获取smtpHost
    private MailSender(final String username, final String password) {
        final String smtpHostName = "smtp." + username.split("@")[1];
        init(smtpHostName, username, password);
    }

    //获取MailSender单例-holder
    private static class SingletonHolder {
        private static final MailSender INSTANCE = new MailSender("1178884049@qq.com", "Sealer5296290");
    }
    //获取MailSender单例-getInstance
    public static MailSender getInstance() {
        return SingletonHolder.INSTANCE;
    }

    //初始化
    private void init(final String smtpHostName, final String username, final String password) {
        this.username = username;
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpHostName);
        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    }

    //发送给个人
    public void send(String recipient, String subject, Object content) throws AddressException, MessagingException {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        message.setSubject(subject);
        message.setContent(content.toString(), "text/html;charset=utf-8");
        Transport.send(message);
    }

    //群发邮件
    public void send(String[] recipients, String subject, Object content) throws AddressException, MessagingException {
        int length = recipients.length;
        Address[] addresses = new InternetAddress[length];
        for (int i = 0; i < length; i++) {
            addresses[i] = new InternetAddress(recipients[i]);
        }
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, addresses);
        message.setSubject(subject);
        message.setContent(content.toString(), "text/html;charset=utf-8");
        Transport.send(message);
    }
}
